using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

using Microsoft.SharePoint.Administration;

namespace Datagility.Shpt.SPDocMirror.Service.Features.SPDocMirrorTimerJob
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("f15b5ad1-896d-414b-8e5d-da52f2bcce05")]
    public class SPDocMirrorTimerJobEventReceiver : SPFeatureReceiver
    {
        const string DOC_MIRROR_JOB_NAME = "SPDocMirrorTimerJob";

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        /// <summary>
        /// Install the timer job
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            //Make sure the job isn't already registered
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == DOC_MIRROR_JOB_NAME)
                {
                    job.Delete();
                    break;
                }
            }

            //Install the job
            MirrorJob mirrorJob = new MirrorJob(DOC_MIRROR_JOB_NAME, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            schedule.Interval = 1;
            mirrorJob.Schedule = schedule;
            //Do not run the job until the user has enabled it
            mirrorJob.IsDisabled = true;
            mirrorJob.Update();
        }

        /// <summary>
        /// Delete the job
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            //Delete the job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == DOC_MIRROR_JOB_NAME)
                    job.Delete();
            }
        }
    }
}
